//
//  AwemeListCell.m
//  Douyin
//
//  Created by Qiao Shi on 2018/7/30.
//  Copyright © 2018年 Qiao Shi. All rights reserved.
//

#import "AwemeListCell.h"
#import "CommentsPopView.h"
#import "SharePopView.h"
//#import "NetworkHelper.h"
#import "NSString+Extension.h"
#import "UIImage+Extension.h"
#import "MHUIKit.h"
#import "NSMutableAttributedString+MHMoment.h"
#import "MHOpenModel.h"
#import "MHRedEnvelopeConfig.h"
#import "MHRedPacketBtn.h"
#define LIKE_BEFORE_TAP_ACTION 1000
#define LIKE_AFTER_TAP_ACTION 2000
#define COMMENT_TAP_ACTION 3000
#define SHARE_TAP_ACTION 4000

@interface AwemeListCell()<SendTextDelegate, HoverTextViewDelegate, AVPlayerUpdateDelegate>
@property (nonatomic, strong) UIView                   *container;
@property (nonatomic ,strong) CAGradientLayer          *gradientLayer;
@property (nonatomic ,strong) UIImageView              *pauseIcon;
@property (nonatomic, strong) UIView                   *playerStatusBar;
@property (nonatomic ,strong) UIImageView              *musicIcon;
@property (nonatomic, strong) UITapGestureRecognizer   *singleTapGesture;
@property (nonatomic, assign) NSTimeInterval           lastTapTime;
@property (nonatomic, assign) CGPoint                  lastTapPoint;
@property(nonatomic, strong) YYTextLayout *contentLayout;
@property(nonatomic, strong) dispatch_source_t currentTimer;

@property(nonatomic, assign) BOOL isExcuting;
@end

@implementation AwemeListCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.backgroundColor = ColorBlackAlpha1;
        self.lastTapTime = 0;
        self.lastTapPoint = CGPointZero;
        [self initSubViews];
        self.redPacketBtn.adjustsImageWhenHighlighted = NO;
    }
    return self;
}

- (void)initSubViews {
    //init player view;
    _playerView = [AVPlayerView new];
    _playerView.delegate = self;
    [self.contentView addSubview:_playerView];
    
    //init hover on player view container
    _container = [UIView new];
    [self.contentView addSubview:_container];
    
    _singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
    [_container addGestureRecognizer:_singleTapGesture];
    
    _gradientLayer = [CAGradientLayer layer];
    _gradientLayer.colors = @[(__bridge id)ColorClear.CGColor, (__bridge id)ColorBlackAlpha20.CGColor, (__bridge id)ColorBlackAlpha40.CGColor];
    _gradientLayer.locations = @[@0.3, @0.6, @1.0];
    _gradientLayer.startPoint = CGPointMake(0.0f, 0.0f);
    _gradientLayer.endPoint = CGPointMake(0.0f, 1.0f);
    [_container.layer addSublayer:_gradientLayer];
    
    _pauseIcon = [[UIImageView alloc] init];
    _pauseIcon.image = [UIImage imageNamed:@"icon_play_pause"];
    _pauseIcon.contentMode = UIViewContentModeCenter;
    _pauseIcon.layer.zPosition = 3;
    _pauseIcon.hidden = YES;
    [_container addSubview:_pauseIcon];
    
    //init hoverTextView
    _hoverTextView = [HoverTextView new];
    _hoverTextView.delegate = self;
    _hoverTextView.hoverDelegate = self;
    [self addSubview:_hoverTextView];
    
    //init player status bar
    _playerStatusBar = [[UIView alloc]init];
    _playerStatusBar.backgroundColor = ColorWhite;
    [_playerStatusBar setHidden:YES];
    [_container addSubview:_playerStatusBar];
    
    //init aweme message
    
    _nickName = [[UILabel alloc]init];
    _nickName.textColor = ColorWhite;
    _nickName.font = BigBoldFont;
    [_container addSubview:_nickName];

    
    _musicIcon = [[UIImageView alloc]init];
    _musicIcon.contentMode = UIViewContentModeScaleAspectFill;
    _musicIcon.image = [UIImage imageNamed:@"icon_home_musicnote3"];
    _musicIcon.masksToBounds = YES;
    [_container addSubview:_musicIcon];
    
    _musicName = [[CircleTextView alloc]init];
    _musicName.textColor = ColorWhite;
    _musicName.font = MediumFont;
    [_container addSubview:_musicName];
    
    _enterBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _enterBtn.backgroundColor = MHColorFromHexString(@"#fe313d");
    _enterBtn.titleLabel.font = MHRegularFont_11;
    [_enterBtn setTitleColor:MHWhiteTextColor forState:0];
//    _enterBtn.titleLabel.textColor = ;
    _enterBtn.layer.cornerRadius = 10;
    _enterBtn.masksToBounds = YES;

    [_container addSubview:_enterBtn];
    
    
    _locationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _locationBtn.backgroundColor = MHColorFromHexString(@"#7C7AD3");
    _locationBtn.titleLabel.font = MHRegularFont_12;
    [_locationBtn setImage:[UIImage imageNamed:@"icon_theme_location"] forState:0];
    [_locationBtn setTitleColor:MHWhiteTextColor forState:0];
    _locationBtn.layer.cornerRadius = 2;
    _locationBtn.masksToBounds = YES;
    _locationBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 5);
    [_container addSubview:_locationBtn];
    
    
    _desc = [MHUIKit cofigYYLableWithTextColor:ColorWhiteAlpha80 font:MediumFont numberOfLines:0 backgroundColor:nil];
    [_container addSubview:_desc];
    
    _desc.numberOfLines = 0;
    _desc.preferredMaxLayoutWidth = SCREEN_WIDTH/5*3;
    
    

    
    

    
    

    
   
    
    
    //init music alum view
    _musicAlum = [MusicAlbumView new];
    [_container addSubview:_musicAlum];
    
    //init share、comment、like action view
    _share = [[UIImageView alloc]init];
    _share.contentMode = UIViewContentModeCenter;
    _share.image = [UIImage imageNamed:@"icon_home_share"];
    _share.userInteractionEnabled = YES;
    _share.tag = SHARE_TAP_ACTION;
    [_share addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)]];
    [_container addSubview:_share];
    
    _shareNum = [[UILabel alloc]init];
    _shareNum.text = @"0";
    _shareNum.textColor = ColorWhite;
    _shareNum.font = SmallFont;
    [_container addSubview:_shareNum];
    
    _comment = [[UIImageView alloc]init];
    _comment.contentMode = UIViewContentModeCenter;
    _comment.image = [UIImage imageNamed:@"icon_home_comment"];
    _comment.userInteractionEnabled = YES;
    _comment.tag = COMMENT_TAP_ACTION;
    [_comment addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)]];
    [_container addSubview:_comment];
    
    _commentNum = [[UILabel alloc]init];
    _commentNum.text = @"0";
    _commentNum.textColor = ColorWhite;
    _commentNum.font = SmallFont;
    [_container addSubview:_commentNum];
    
    _favorite = [FavoriteView new];
   
    [_container addSubview:_favorite];
    
    _favoriteNum = [[UILabel alloc]init];
    _favoriteNum.text = @"0";
    _favoriteNum.textColor = ColorWhite;
    _favoriteNum.font = SmallFont;
    [_container addSubview:_favoriteNum];
    
    //init avatar
    CGFloat avatarRadius = 25;
    _avatar = [[UIImageView alloc] init];
    _avatar.image = [UIImage imageNamed:@"img_find_default"];
    _avatar.layer.cornerRadius = avatarRadius;
    _avatar.layer.borderColor = ColorWhiteAlpha80.CGColor;
    _avatar.layer.borderWidth = 1;
    [_container addSubview:_avatar];
    
    [_container addSubview:self.progressBar];
    
    
    if([AXAppDelegate sharedDelegate].isAuthorizationExpired)
    {
        
        //    _redPacketStatusLabel = [[UILabel alloc]init];
        //    _redPacketStatusLabel.textColor = ColorWhite;
        //    _redPacketStatusLabel.font = BigBoldFont;
        //    [_container addSubview:_redPacketStatusLabel];
        
       
        
        
        self.redPacketBtn = [MHRedPacketBtn buttonWithType:UIButtonTypeCustom];
        [self.redPacketBtn setImage:[UIImage imageNamed:@"ic_video_package_yl"] forState:UIControlStateSelected];
        [self.redPacketBtn setImage:[UIImage imageNamed:@"ic_video_package_yk"] forState:UIControlStateHighlighted | UIControlStateSelected];
        [self.redPacketBtn setTitleColor:MHWhiteTextColor forState:0];
        self.redPacketBtn.masksToBounds = YES;
        self.redPacketBtn.hidden = YES;
        [_container addSubview:self.redPacketBtn];
        
        self.redPacketLeftLabel = [[UILabel alloc]init];
        self.redPacketLeftLabel.textColor = MHTextColorDD;
        self.redPacketLeftLabel.font = MHRegularFont_12;
        self.redPacketLeftLabel.hidden = YES;
        [_container addSubview:self.redPacketLeftLabel];
        
        self.openRedPacketView = [[MHOpenRedPacketView alloc] init];
        self.openRedPacketView.hidden = YES;
        [self addSubview: self.openRedPacketView];
        
        self.redPacketStatusLabel = [[UILabel alloc]init];
        self.redPacketStatusLabel.textColor = MHWhiteTextColor;
        self.redPacketStatusLabel.font = MHRegularFont_12;
        self.redPacketStatusLabel.textAlignment = NSTextAlignmentCenter;
        [_container addSubview:self.redPacketStatusLabel];
    }
    

    
}


-(void)prepareForReuse {
    [super prepareForReuse];
    
    _isPlayerReady = NO;
    [_playerView cancelLoading];
    [_pauseIcon setHidden:YES];
    self.progressBar.hidden = YES;
    self.progressBar.progress = 0;
    self.focus.userInteractionEnabled = YES;
    [_hoverTextView.textView setText:@""];
    [_avatar setImage:[UIImage imageNamed:@"img_find_default"]];
    
    [_musicAlum resetView];
    [_favorite resetView];
    [_focus resetView];
    self.redPacketBtn.userInteractionEnabled = YES;
    self.redPacketStatusLabel.text = @"";
}

-(void)layoutSubviews {
    [super layoutSubviews];
    [self createLayout];
}

//修复布局问题;

-(void) createLayout
{
    _playerView.frame = self.bounds;
    _container.frame = self.bounds;
    
    _pauseIcon.frame = CGRectMake(CGRectGetMidX(self.bounds) - 50, CGRectGetMidY(self.bounds) - 50, 100, 100);
    
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    _gradientLayer.frame = CGRectMake(0, self.frame.size.height - 500, self.frame.size.width, 500);
    [CATransaction commit];
    
    [_playerStatusBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.bottom.equalTo(self).inset(49.5f+ zh_safeAreaHeight());
        make.width.mas_equalTo(1.0f);
        make.height.mas_equalTo(0.5f);
    }];
    
    
    [self.progressBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.bottom.equalTo(self).inset(49.5f+ zh_safeAreaHeight());
        make.width.equalTo(self);
        make.height.mas_equalTo(1.0f);
    }];
    
    [_desc mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(10);
        make.bottom.equalTo(self.playerStatusBar.mas_top).offset(-10);
        make.width.mas_lessThanOrEqualTo(SCREEN_WIDTH/5*3);
//        make.height.equalTo(@(self->_desc.textLayout.textBoundingSize.height));
    }];
    
    [_musicIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(60);
        make.top.equalTo(self).offset(STATUS_BAR_HEIGHT + 6);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(30);
    }];
    
    [_musicName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.musicIcon.mas_right);
        make.centerY.equalTo(self.musicIcon);
        make.width.mas_equalTo(SCREEN_WIDTH/2);
        make.height.mas_equalTo(20);
    }];
    
   
    
    
    [_nickName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(10);
        make.bottom.equalTo(self.desc.mas_top).inset(5);
        make.width.mas_lessThanOrEqualTo(SCREEN_WIDTH/4*3 + 30);
    }];
    
    [_locationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(10);
        make.bottom.equalTo(self.nickName.mas_top).inset(5);
        make.height.equalTo(@24);
    }];
    
    
    [self.redPacketLeftLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(15);
        make.bottom.equalTo(self.locationBtn.mas_top).inset(5);
        make.width.mas_lessThanOrEqualTo(SCREEN_WIDTH/4*3 + 30);
    }];
    
    [self.redPacketBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.redPacketLeftLabel.mas_left).offset(3);
        make.bottom.equalTo(self.redPacketLeftLabel.mas_top).offset(-5);
    }];
    
    
    [self.redPacketStatusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.redPacketBtn);
        make.bottom.equalTo(self.redPacketBtn.mas_bottom).offset(-4);
    }];
    
    
    [_enterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.mas_right).offset(-10);
        make.centerY.equalTo(self.musicIcon);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(20);
    }];
    
    [_musicAlum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.playerStatusBar).offset(-10);
        make.right.equalTo(self).inset(10);
        make.width.height.mas_equalTo(50);
    }];
    [_share mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.musicAlum.mas_top).inset(50);
        make.right.equalTo(self).inset(10);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(45);
    }];
    [_shareNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.share.mas_bottom);
        make.centerX.equalTo(self.share);
    }];
    [_comment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.share.mas_top).inset(25);
        make.right.equalTo(self).inset(10);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(45);
    }];
    [_commentNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.comment.mas_bottom);
        make.centerX.equalTo(self.comment);
    }];
    [_favorite mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.comment.mas_top).inset(25);
        make.right.equalTo(self).inset(10);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(45);
    }];
    
    [_favoriteNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.favorite.mas_bottom);
        make.centerX.equalTo(self.favorite);
    }];
    CGFloat avatarRadius = 25;
    [_avatar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.favorite.mas_top).inset(35);
        make.right.equalTo(self).inset(10);
        make.width.height.mas_equalTo(avatarRadius*2);
    }];
    [_focus mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.avatar);
        make.centerY.equalTo(self.avatar.mas_bottom);
        make.width.height.mas_equalTo(24);
    }];
    [self.openRedPacketView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.locationBtn.mas_top);
        make.left.equalTo(self);
        make.width.equalTo(@126);
        make.height.equalTo(@150);
    }];
}

-(YLProgressBar *)progressBar
{
    if (!_progressBar) {
        _progressBar = [YLProgressBar new];
        NSArray *tintColors = @[[UIColor whiteColor]];
        
        _progressBar.type               = YLProgressBarTypeFlat;
        _progressBar.progressTintColors = tintColors;
        _progressBar.hideStripes        = YES;
        _progressBar.hideTrack          = YES;
    }
    return _progressBar;
}

- (void)onSendText:(NSString *)text {
    @weakify(self);
    [[[[MHHTTPService sharedInstance] publishCommentWithRecentId:_aweme.recentId content:text parentId: 0 ] mh_parsedResults] subscribeNext:^(MHComment *comentResponse) {
        @strongify(self);
        [UIWindow showTips:@"评论成功"];
        self.aweme.commentCount = self.aweme.commentCount +1;
        [self.commentNum setText:[NSString formatCount:_aweme.commentCount]];
    } error:^(NSError *error) {
        [UIWindow showTips:@"评论失败"];
    }];
}


-(void)hoverTextViewStateChange:(BOOL)isHover {
    _container.alpha = isHover ? 0.0f : 1.0f;
}

- (void)handleGesture:(UITapGestureRecognizer *)sender {
    switch (sender.view.tag) {
        case COMMENT_TAP_ACTION: {
            CommentsPopView *popView = [[CommentsPopView alloc] initWithAwemeId:_aweme];
            __weak __typeof(self)weakSelf = self;
            popView.commentSuccessBlock = ^{
        
                weakSelf.aweme.commentCount = weakSelf.aweme.commentCount +1;
                [weakSelf.commentNum setText:[NSString formatCount:weakSelf.aweme.commentCount]];
            };
            [popView show];
            break;
        }
        case SHARE_TAP_ACTION: {
            SharePopView *popView = [[SharePopView alloc] initWithAwmeModel:_aweme];
            
            [popView show];
            break;
        }
        default: {
            //获取点击坐标，用于设置爱心显示位置
            CGPoint point = [sender locationInView:self.container];
            //获取当前时间
            NSTimeInterval time = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
            //判断当前点击时间与上次点击时间的时间间隔
            if(time - self.lastTapTime > 0.25f) {
                //推迟0.25秒执行单击方法
                [self performSelector:@selector(singleTapAction) withObject:nil afterDelay:0.25f];
            }else {
                //取消执行单击方法
                [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(singleTapAction) object: nil];
                //执行连击显示爱心的方法
                [self showLikeViewAnim:point oldPoint:self.lastTapPoint];
                CGPoint likePoint = [sender locationInView:_favorite];
                if (!_aweme.isHaveLike && ![_favorite.layer containsPoint:likePoint]) {
                   
                    @weakify(self);
                    _favorite.userInteractionEnabled = NO;
                    [[[MHHTTPService sharedInstance] likeRecentStoryWithRecentId:_aweme.recentId type:1] subscribeNext:^(id x) {
                        @strongify(self);
                        self.aweme.isHaveLike = YES;
                        self.aweme.likeCount =  self.aweme.likeCount + 1;
                        [self.favorite  startAttriAnim:YES];
                        self.favorite.userInteractionEnabled = YES;
                    } error:^(NSError *error) {
                        self.favorite.userInteractionEnabled = YES;
                    }];
                }
                
            }
            //更新上一次点击位置
            self.lastTapPoint = point;
            //更新上一次点击时间
            self.lastTapTime =  time;
            break;
        }
    }
    
}

- (void)singleTapAction {
    if([self.hoverTextView isFirstResponder]) {
        [self.hoverTextView resignFirstResponder];
    }else {
        [self showPauseViewAnim:[self.playerView rate]];
        [self.playerView updatePlayerState];
    }
}

//暂停播放动画
- (void)showPauseViewAnim:(CGFloat)rate {
    if(rate == 0) {
        [UIView animateWithDuration:0.25f
                         animations:^{
                             self.pauseIcon.alpha = 0.0f;
                         } completion:^(BOOL finished) {
                             [self.pauseIcon setHidden:YES];
                         }];
    }else {
        [_pauseIcon setHidden:NO];
        _pauseIcon.transform = CGAffineTransformMakeScale(1.8f, 1.8f);
        _pauseIcon.alpha = 1.0f;
        [UIView animateWithDuration:0.25f delay:0
                            options:UIViewAnimationOptionCurveEaseIn animations:^{
                                self.pauseIcon.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
                            } completion:^(BOOL finished) {
                            }];
    }
}

//连击爱心动画
- (void)showLikeViewAnim:(CGPoint)newPoint oldPoint:(CGPoint)oldPoint {
    UIImageView *likeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_home_like_after"]];
    CGFloat k = ((oldPoint.y - newPoint.y)/(oldPoint.x - newPoint.x));
    k = fabs(k) < 0.5 ? k : (k > 0 ? 0.5f : -0.5f);
    CGFloat angle = M_PI_4 * -k;
    likeImageView.frame = CGRectMake(newPoint.x, newPoint.y, 80, 80);
    likeImageView.transform = CGAffineTransformScale(CGAffineTransformMakeRotation(angle), 0.8f, 1.8f);
    [self.container addSubview:likeImageView];
    [UIView animateWithDuration:0.2f
                          delay:0.0f
         usingSpringWithDamping:0.5f
          initialSpringVelocity:1.0f
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         likeImageView.transform = CGAffineTransformScale(CGAffineTransformMakeRotation(angle), 1.0f, 1.0f);
                     }
                     completion:^(BOOL finished) {
                         [UIView animateWithDuration:0.5f
                                               delay:0.5f
                                             options:UIViewAnimationOptionCurveEaseOut
                                          animations:^{
                                              likeImageView.transform = CGAffineTransformScale(CGAffineTransformMakeRotation(angle), 3.0f, 3.0f);
                                              likeImageView.alpha = 0.0f;
                                          }
                                          completion:^(BOOL finished) {
                                              [likeImageView removeFromSuperview];
                                          }];
                     }];
}

//加载动画
-(void)startLoadingPlayItemAnim:(BOOL)isStart {
    if (isStart) {
        self.playerStatusBar.backgroundColor = ColorWhite;
        [self.playerStatusBar setHidden:NO];
        [self.playerStatusBar.layer removeAllAnimations];
        
        CAAnimationGroup *animationGroup = [[CAAnimationGroup alloc]init];
        animationGroup.duration = 0.5;
        animationGroup.beginTime = CACurrentMediaTime() + 0.5;
        animationGroup.repeatCount = MAXFLOAT;
        animationGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        
        CABasicAnimation * scaleAnimation = [CABasicAnimation animation];
        scaleAnimation.keyPath = @"transform.scale.x";
        scaleAnimation.fromValue = @(1.0f);
        scaleAnimation.toValue = @(1.0f * SCREEN_WIDTH);
        
        CABasicAnimation * alphaAnimation = [CABasicAnimation animation];
        alphaAnimation.keyPath = @"opacity";
        alphaAnimation.fromValue = @(1.0f);
        alphaAnimation.toValue = @(0.5f);
        [animationGroup setAnimations:@[scaleAnimation, alphaAnimation]];
        [self.playerStatusBar.layer addAnimation:animationGroup forKey:nil];
    } else {
        [self.playerStatusBar.layer removeAllAnimations];
        [self.playerStatusBar setHidden:YES];
    }
    
}

// AVPlayerUpdateDelegate
-(void)onProgressUpdate:(CGFloat)current total:(CGFloat)total {
    _progressBar.hidden = (current <= 0 || current >= total);
    if (current == 0) {
        _progressBar.progress = 0;
    }else
    {
         [_progressBar setProgress:current/total animated:YES];
    }
}

-(void)onPlayItemStatusUpdate:(AVPlayerItemStatus)status {
    switch (status) {
        case AVPlayerItemStatusUnknown:
            [self startLoadingPlayItemAnim:YES];
            break;
        case AVPlayerItemStatusReadyToPlay:
            [self startLoadingPlayItemAnim:NO];
            
            self.isPlayerReady = YES;
            [self.musicAlum startAnimation:12];
            
            if(_onPlayerReady) {
                _onPlayerReady();
            }
            break;
        case AVPlayerItemStatusFailed:
            [self startLoadingPlayItemAnim:NO];
            [UIWindow showTips:@"加载失败"];
            break;
        default:
            break;
    }
}

- (void)initData:(MHAwemeModel *)aweme {
    _aweme = aweme;
     __weak __typeof(self) wself = self;
    [_enterBtn setTitle:aweme.isInCircle ? @"进入圈子" : @"加入圈子"  forState:0];
    _favorite.recentId = aweme.recentId;
    [_favorite layoutIfNeeded];
    [_favorite setNeedsLayout];
    _favorite.favoriteBefore.hidden = aweme.isHaveLike ;
    _favorite.favoriteAfter.hidden = !aweme.isHaveLike;
    _favorite.successBlcok = ^(BOOL isLike) {
        wself.aweme.isHaveLike = isLike;
        wself.aweme.likeCount =  wself.aweme.likeCount + (isLike ? 1: -1 );
    };
    
    
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:aweme.content?:@""];
    attr.yy_color = MHWhiteTextColor;
    attr.yy_font = MediumFont;
    [attr mh_regexContentWithWithEmojiImageFontSize:14];
    _desc.attributedText= attr;
    
    
    @weakify(self);
    [RACObserve(self.aweme, likeCount) subscribeNext:^(NSNumber *likeCount) {
        @strongify(self);
        [self.favoriteNum setText:[NSString formatCount:[likeCount integerValue]]];
    }];
    if (aweme.vedioObj.videoURL.absoluteString.length > 0) {
        [_playerView setPlayerWithUrl:aweme.vedioObj.videoURL.absoluteString];
    }else
    {
    }
    [_nickName setText:[NSString stringWithFormat:@"@%@",aweme.publishUserName]];
    
    
    
    [self configWithRedInfoWith:aweme];
    
 if(MHStringIsEmpty(aweme.content))
 {
     
 }
    

    [_commentNum setText:[NSString formatCount:aweme.commentCount]];
    [_shareNum setText:[NSString formatCount:aweme.shareCount]];
    
    
    self.locationBtn.hidden = !aweme.location.isShowLocation;
    if (aweme.location.isShowLocation) {
        [self.locationBtn setTitle:[NSString stringWithFormat:@" %@",aweme.location.areaName] forState: 0];
    }
    
    [_musicIcon yy_setImageWithURL:[NSURL URLWithString:aweme.fullCoverUrl] placeholder:MHDefaultAvatar(MHDefaultAvatarTypeDefualt) options:nil completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
        wself.musicIcon.image = [image drawCircleImage];
    }];
    if(aweme.circleIntro.length <= 0)
    {
        aweme.circleIntro = @"圈主很懒，什么都没有说";
    }
    
    [_musicName setText:[NSString stringWithFormat:@"【%@】 %@",aweme.circleName,aweme.circleIntro]];
    
    [_avatar yy_setImageWithURL:[NSURL URLWithString:aweme.allPublishUserHeadPic] placeholder:MHDefaultAvatar(MHDefaultAvatarTypeDefualt) options:nil completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
        wself.avatar.image = [image drawCircleImage];
    }];
    
    if (aweme.songInfo) {
        [self.musicAlum.album yy_setImageWithURL:[NSURL URLWithString:aweme.songInfo.fullCoverUrl ] placeholder:[UIImage imageNamed:@"icon_app"] options:nil completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
            self.musicAlum.album.image  = [image drawCircleImage];
        }];
//        self.musicAlum.album.image = [[UIImage imageNamed:@"icon_app"] drawCircleImage];
    }else
    {
        self.musicAlum.album.image = [[UIImage imageNamed:@"icon_app"] drawCircleImage];
    }
//    [self createLayout];
//    [self layoutIfNeeded];
//    [self setNeedsLayout];
  
    
}

-(void) configWithRedInfoWith:(MHAwemeModel *) model
{
    if (model.redInfo) {
        self.redPacketLeftLabel.hidden = false;
        self.redPacketBtn.hidden = false;
        self.redPacketStatusLabel.hidden = false;
        if (model.redInfo.surplusNum) {
            self.redPacketLeftLabel.text = [NSString stringWithFormat:@"剩余%d个",model.redInfo.surplusNum];
        }else
        {
            self.redPacketLeftLabel.text = @"";
        }
        [self.redPacketBtn configRedPacketWithRedPacketWithRedInfo:model.redInfo redPacketPositon:RedPackePostionInVideo];
        //已领取
        //未领取
        self.redPacketBtn.selected = model.redInfo.isHaveReceived;
        
        if (model.redInfo.isHaveReceived) {
            self.redPacketStatusLabel.text = @"已领取";
//            self.redPacketStatusLabel.hidden = false;
        }else
        {
        }
        
        //RedPacketGoing
        switch (model.redInfo.status) {
            case RedPacketFinish:
                self.redPacketBtn.selected = YES;
                self.redPacketBtn.highlighted = YES;
                self.redPacketStatusLabel.text = @"已领完";
                break;
            case RedPacketExpired:
                self.redPacketBtn.selected = YES;
                self.redPacketBtn.highlighted = YES;
                self.redPacketStatusLabel.text = @"已过期";
                break;
            default:
                break;
        }
        
    }else
    {
        self.redPacketLeftLabel.hidden = YES;
        self.redPacketBtn.hidden = YES;
        self.redPacketStatusLabel.hidden = YES;
        
    }
}



- (void)redPacketCoutDown {

//    if (self.isExcuting) {
//        return;
//    }
//    self.isExcuting = YES;
    
    YYCache *cache=[YYCache cacheWithName:MHCacheGlobleKey];
    MHRedEnvelopeConfig *config  =  [cache objectForKey:MHRedPacketConfig];
    __block NSInteger time = ((config == nil)? 5 : config.countdown); //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    self.currentTimer = timer;
    dispatch_source_set_timer(timer,DISPATCH_TIME_NOW,1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(timer, ^{
        
        if(time <= 0){
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.redPacketBtn.userInteractionEnabled = YES;
                [self openRedPacketWithRedInfo:self->_aweme.redInfo];
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                self.redPacketStatusLabel.text = [NSString stringWithFormat:@"%d",seconds];
                self.redPacketBtn.userInteractionEnabled = NO;
                
            });
            
            time--;
        }
    });
    
    dispatch_resume(timer);
}


-(void) openRedPacketWithRedInfo:(MHRedInfo *) redInfo
{
    @weakify(self);
    [[[[MHHTTPService sharedInstance] openRedPacketWithRedId:redInfo.autoId lat:self.location.coordinate.latitude lon:self.location.coordinate.longitude] mh_parsedResults] subscribeNext:^(MHOpenModel *openModel) {
        @strongify(self);
        self.openRedPacketView.hidden = false;
        self.openRedPacketView.remakLabel.text = openModel.title;
        
        self.aweme.redInfo.isHaveReceived = YES;
        NSMutableAttributedString *amountAttri =  [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.2f元",openModel.amount]];
        [amountAttri addAttribute:NSFontAttributeName value:MHRegularFont_20 range:NSMakeRange(0, amountAttri.length - 1)];
        //添加文字颜色
        
         [amountAttri addAttribute:NSFontAttributeName value:MHRegularFont_10 range:NSMakeRange(amountAttri.length - 1, 1)];
        [amountAttri addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, amountAttri.length)];

        self.openRedPacketView.amountLabel.attributedText = amountAttri;
        [self hiddenSubRedPacketView:YES];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.openRedPacketView.hidden = YES;
            [self hiddenSubRedPacketView:NO];
            self.redPacketStatusLabel.text = @"已领取";
            self.redPacketBtn.selected = YES;
            self.redPacketBtn.highlighted = YES;
        });
    } error:^(NSError *error) {
        if (error.code == 3 ) {
            self.openRedPacketView.hidden = YES;
            [self hiddenSubRedPacketView:NO];
            self.redPacketStatusLabel.text = @"已抢完";
            self.redPacketBtn.selected = YES;
            self.redPacketBtn.highlighted = YES;
        }else if(error.code == 4)
        {
            self.openRedPacketView.hidden = YES;
            [self hiddenSubRedPacketView:NO];
            self.redPacketStatusLabel.text = @"已过期";
            self.redPacketBtn.selected = YES;
            self.redPacketBtn.highlighted = YES;
        }
    }];
}

-(void) cancelTime
{
    if (self.currentTimer) {
        dispatch_source_cancel(self.currentTimer);
       self.redPacketStatusLabel.text = @"";
    }
}

-(void) hiddenSubRedPacketView:(BOOL)hidden
{
    self.redPacketBtn.hidden = hidden;
    self.redPacketStatusLabel.hidden = hidden;
    self.redPacketLeftLabel.hidden = hidden;
}

-(void)play {
    
    [_playerView play];
    [_pauseIcon setHidden:YES];
}

-(void)pause {
    [_playerView pause];
    [_pauseIcon setHidden:NO];
}

-(void)replay {
    self.progressBar.progress = 0;
    [_playerView replay];
    [_pauseIcon setHidden:YES];
}
-(void)dealloc
{
    NSLog(@"cccc");
     _playerView = nil;
}
//- (void)dealloc {
//    _playerView = nil;
//}

@end
